﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore;
using AVISOutBound.SSOServer.EntityFrameworkCore;
using AVISOutBound.SSOServer.Web.Models.IdentityConfig;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Mvc;

namespace AVISOutBound.SSOServer.Web.Controllers
{
    public class IdentityConfigController:SSOServerControllerBase
    {
        private readonly IDbContextProvider<SSOServerDbContext> _dbContextProvider;

        public IdentityConfigController(IDbContextProvider<SSOServerDbContext> dbContextProvider)
        {
            _dbContextProvider = dbContextProvider;
        }
        [UnitOfWork]
        public async Task<IActionResult> CreateClientAsync(CreateClientModel model)
        {
            var dbContext = _dbContextProvider.GetDbContext();
            dbContext.Clients.Add(new Client
            {
                ClientId = model.ClientId,
                ClientName = model.ClientName,
                AllowedGrantTypes = model.GrantTypes,

                AllowAccessTokensViaBrowser = true,
                RequireConsent = false,

                ClientSecrets =
                {
                    new Secret(model.ClientSecret.Sha256())
                },

                RedirectUris = model.RedirectUris,
                PostLogoutRedirectUris = model.PostLogoutRedirectUris,

                AllowedScopes = new List<string>()
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                }.Concat(model.AllowedScopes).ToList(),
            }.ToEntity());

            return Ok();
        }

        [UnitOfWork]
        public async Task<IActionResult> CreateApiResourceAsync(CreateApiResourceModel model)
        {
            var dbContext = _dbContextProvider.GetDbContext();

            dbContext.ApiResources.Add(new ApiResource()
            {
                Scopes = model.Scopes.Select(x=>new Scope(x)).ToList(),
                Enabled = true,
                ApiSecrets = { new Secret(model.Secret.Sha256()) },
                Description = "",
                DisplayName = "",
                Name = model.Name,
                UserClaims = { JwtClaimTypes.Subject },
            }.ToEntity());

            return Ok();
        }
    }
}
